class Carousel{
    constructor(classname){
        this.container = document.querySelector('.'+classname);
        this.leftBtn = this.container.querySelector('.leftBtn')
        this.rightBtn = this.container.querySelector('.rightBtn')
        this.ul = this.container.querySelector('ul')
        this.ol = this.container.querySelector('ol')
        this.firstLi = this.ul.firstElementChild.cloneNode(true)
        this.index = 1
        this.flag = true
        this.timerId = null
    }
    handlerUl(){
        this.ul.insertBefore(this.ul.lastElementChild.cloneNode(true),this.ul.firstElementChild)
        this.ul.appendChild(this.firstLi)
        this.ul.style.left = -this.firstLi.offsetWidth + "px"
        this.ul.style.width = this.ul.children.length * this.firstLi.offsetWidth + "px"
    }
    handlerOl(){
        for(let i=0;i<this.ul.children.length;i++){
            let li = document.createElement('li')
            this.ol.appendChild(li)
            if(i===0) li.style.backgroundColor = 'red'
        }
    }
    rightMove(){
        if(!this.flag) return false;
        this.flag = false
        this.index++
        this.move()
    }
    init(){
        this.handlerOl()
        this.handlerUl()
        this.rightBtn.onclick = ()=>{
            this.rightMove()
            return false;
        }
        // console.log(this)
        this.leftBtn.onclick = ()=>{
            if(!this.flag) return false;
            this.flag = false
            this.index--
            this.move()
            return false;
        }
        for(let i=0;i<this.ol.children.length;i++){
            this.ol.children[i].onclick = ()=>{
                if(!this.flag) return false;
                this.flag = false
                this.index = i+1
                this.move()
            }
        }
        this.auto()
        this.container.onmouseover = ()=>{
            clearInterval(this.timerId)
        }
        this.container.onmouseout = ()=>{
            this.auto()
        }
    }
    auto(){
        this.timerId = setInterval(()=>{
            this.rightMove()
        },1500)
    }
    move(){
        tool.move(this.ul,{
            left:-this.index * this.firstLi.offsetWidth
        },()=>{
            if(this.index === this.ul.children.length-1){
                this.index = 1;
                this.ul.style.left = -this.index * this.firstLi.offsetWidth + "px"
            }
            if(this.index === 0){
                this.index = this.ul.children.length-2;
                this.ul.style.left = -this.index * this.firstLi.offsetWidth + "px"
            }
            for(let i=0;i<this.ol.children.length;i++){
                this.ol.children[i].style.backgroundColor = '#000'
            }
            this.ol.children[this.index-1].style.backgroundColor = 'red';
            this.flag = true
        })
    }
}

var c = new Carousel('carousel')
c.init()